# 精度评价
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
from scipy.stats import pearsonr

plt.rcParams['font.sans-serif'] = [u'SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['font.family'] = 'SimHei'

def model_accuracy_plot(model,X_train,y_train,X_test,y_test,draw=True,title='default'):
    model.fit(X_train, y_train)
    y_pred = model.predict(X_test)
    y_pred = np.maximum(y_pred, 0)
    if(draw):
        plotPicturesEx(y_test.flatten(),y_pred.flatten(),defaultTitle=title)
    return accuracyAssessment(y_test,y_pred)

def chloropyll_split_train_test(all_data,percent = 0.8):
    from sklearn.model_selection import train_test_split
    all_features = pd.DataFrame(data=None, columns=(all_data.iloc[:, 1:-2]).columns)

    X_train_g = None;
    X_test_g = None;
    y_train_g = None;
    y_test_g = None;

    feature_num = -2

    feature_cols = None
    # 数据等值间隔
    gapValList = [0, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48, 40.96, 1000]
    for row in range(0, 4):
        for col in range(0, 3):
            idx = row * 3 + col
            curCHL = all_data[(all_data.in_situ_chl < gapValList[idx + 1]) & (all_data.in_situ_chl > gapValList[idx])]
            X, y = curCHL.iloc[:, 1:feature_num].values, curCHL.iloc[:, -2:-1].values
            feature_cols = curCHL.iloc[:, 1:feature_num].columns
            X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
            if (X_train_g is None):
                X_train_g = np.array(X_train)
                X_test_g = np.array(X_test)
                y_train_g = np.array(y_train)
                y_test_g = np.array(y_test)
            else:
                X_train_g = np.append(X_train_g, X_train, axis=0)
                X_test_g = np.append(X_test_g, X_test, axis=0)
                y_train_g = np.append(y_train_g, y_train, axis=0)
                y_test_g = np.append(y_test_g, y_test, axis=0)

    # %%



    return  X_train_g,y_train_g,X_test_g,y_test_g

def scaler_data(X_train,X_test):
    # 构建标准化scaler
    X_All = np.append(X_train, X_test, axis=0)
    import sklearn.preprocessing as preprocessing
    scaler = preprocessing.StandardScaler().fit(X_All)

    print("===========================")
    # 执行标准化
    X_train = scaler.transform(X_train)
    X_test = scaler.transform(X_test)
    return X_train,X_test,scaler

def accuracyAssessment(tureVals, preVals, is_print=True):
    # 可解释方差得分
    from sklearn.metrics import explained_variance_score
    score = explained_variance_score(tureVals, preVals)

    # 平均绝对误差
    from sklearn.metrics import mean_absolute_error
    merror = mean_absolute_error(tureVals, preVals)

    # 均方误差
    from sklearn.metrics import mean_squared_error
    mse = mean_squared_error(tureVals, preVals)

    # 均方误差
    from sklearn.metrics import mean_squared_log_error
    msle = mean_squared_log_error(tureVals, preVals)

    # 中位数绝对误差
    from sklearn.metrics import median_absolute_error
    medAE = median_absolute_error(tureVals, preVals)

    # R² score
    from sklearn.metrics import r2_score
    r2Score = r2_score(tureVals, preVals)

    if(is_print):
        print(
            'explained variance score:{},\nmean absolute error:{},\nmean squared error:{},\nmean squared log error:{} \nmedian_absolute_error:{}, \nr2Score:{}'.format(
                score, merror, mse, msle, medAE, r2Score))

    return [score, merror, mse, msle, medAE, r2Score]


def plotPictures(tureVals, preVals,defaultTitle=''):

    plt.figure(1, figsize=(6, 6))
    plt.title(defaultTitle)
    plt.xlabel('predict (mg/L)')
    plt.ylabel('in-situ (mg/L)')
    plt.xlim([0, 25])
    plt.ylim([0, 25])
    plt.plot([0,25],[0,25],color='r')
    plt.scatter(tureVals, preVals)

def plotPicturesEx(tureVals, preVals,defaultTitle=''):
    numpy_data = np.array([tureVals,preVals])
    df = pd.DataFrame(data=numpy_data.T, columns=["trueVals", "predictVals"])
    plot = sns.jointplot(x="predictVals", y="trueVals", data=df, kind="reg")
    plot.fig.suptitle(defaultTitle)
    plot.ax_marg_x.set_xlim(0, 50)
    plot.ax_marg_y.set_ylim(0, 50)
    plot.set_axis_labels(xlabel='predict(mg/L)',ylabel='in-situ(mg/L)')
    # plot.show()
    plot.savefig(defaultTitle+'.png',dpi=300)

def fun(num):
    k == 1
    while(num) :
        k*=num%10
        num/=10
    else:
        return k

def number_product() :
    num = int(input("请输入一个正整数，并按回车继续:"))
    print("这个数字的各位上的数字之积为:" , fun(num)) ;

def is_prime(num):
    #根据质数的定义，其必须大于0
    if num == 1:
        return False
    #循环需要判断的次数
    for i in range(2, num // 2 + 1):
        #如果该数有其他的因子返回False，即不是质数
        if num % i == 0:
            return False
    return True

def print_prime():
    a = 1
    num = int(input("接收一个数字:"))
    while a<=5:
        if(is_prime(num)):
            print(num)
            a += 1
        num += 1

def print_multiplication_table():
    for i in range(1,10):
        for j in range(1,i+1):
            print('{}*{}={}'.format(j,i,i*j),end=' ')
        print()

def unique_list(mlist):
    mset = set(mlist)
    return  list(mset)

class Cube:
    def __init__(self,x,y,z):
        self.width = x
        self.length = y
        self.height = z

    def volume(self):
        return  self.width*self.length*self.height

class Rectangle:
    def __init__(self,x,y):
        self.width = x
        self.length = y

    def area(self):
        return  self.width*self.length


def grade_level(fs):
    if(fs >= 90):
        return 'A'
    elif fs >=60:
        return 'B'
    else:
        return 'C'

def reverse_string(mstr):
    return mstr[-1::-1]

def print_even(numlist):
    retList = []
    for i in numlist:
        if(i % 2 == 0):                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
            retList.append(i)
    return retList


if __name__ == '__main__':
    vec = [[1, 2], [3., 4]]
    mvec = reverse_string('nihaliage')
    print(mvec)








